﻿using System;
using System.Drawing;
using System.Text;
//using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;

namespace IDCardTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            cbDevType.Items.Add("GWI");
            cbDevType.Items.Add("JINGLUN");
            cbDevType.Items.Add("HUASHI100A");
            cbDevType.Items.Add("HUASHI100AU");
            cbDevType.Items.Add("WR300");
            cbDevType.SelectedIndex = 0;
        }

        #region  C++动态库 DLL Import
        /// <summary>
        /// 设置参数
        /// </summary>
        /// <param name="deType">设备类型</param>
        /// <param name="com">串口号</param>
        /// <param name="aud">串口参数</param>
        /// <param name="reCode">返回码</param>
        /// <returns>System.Int32</returns>
        [DllImport("GWI_IDCard_Driver.dll", EntryPoint = "IDCard_SetDeviceParam")]
        private static extern int IDCard_SetDeviceParam(String deType, String com, String aud, StringBuilder reCode);
        /// <summary>
        /// 设置日志级别
        /// </summary>
        /// <param name="level">日志级别</param>
        /// <returns>void</returns>
        [DllImport("GWI_IDCard_Driver.dll", EntryPoint = "IDCard_SetDeviceTraceLevel")]
        private static extern void IDCard_SetDeviceTraceLevel(int level);
        /// <summary>
        /// 打开设备
        /// </summary>
        /// <param name="reCode">返回码</param>
        /// <returns>System.Int32</returns>
        [DllImport("GWI_IDCard_Driver.dll", EntryPoint = "IDCard_OpenDevice")]
        private static extern int IDCard_OpenDevice(StringBuilder reCode);
        /// <summary>
        /// 读二代身份证
        /// </summary>
        /// <param name="dwTimeOut">超时时间</param>
        /// <param name="msg">返回信息</param>
        /// <param name="reCode">返回码</param>
        /// <returns>System.Int32</returns>
        [DllImport("GWI_IDCard_Driver.dll", EntryPoint = "IDCard_ReadIDCardMsg")]
        public static extern int IDCard_ReadIDCardMsg(int dwTimeOut, StringBuilder msg, StringBuilder reCode);
        /// <summary>
        /// 关闭设备
        /// </summary>
        /// <param name="reCode">返回码</param>
        /// <returns>System.Int32</returns>
        [DllImport("GWI_IDCard_Driver.dll", EntryPoint = "IDCard_CloseDevice")]
        private static extern int IDCard_CloseDevice(StringBuilder reCode);
        /// <summary>
        /// 读二代身份证（带照片）
        /// </summary>
        /// <param name="photoName">照片路径</param>
        /// <param name="dwTimeOut">超时时间</param>
        /// <param name="msg">返回数据</param>
        /// <param name="pszRcCode">返回码</param>
        /// <returns>System.Int32</returns>
        [DllImport("GWI_IDCard_Driver.dll", EntryPoint = "IDCard_ReadIDCardMsgExt")]
        private static extern int IDCard_ReadIDCardMsgExt(String photoName, int dwTimeOut, StringBuilder msg, StringBuilder pszRcCode);

        //功能描述：获取取设备信息。
        [DllImport("GWI_IDCard_Driver.dll", EntryPoint = "IDCard_GetDevid")]
        public static extern int IDCard_GetDevid(int dwTimeOut, StringBuilder devid, StringBuilder pszRcCode);


        //功能描述：读取身份证ID号。
        //输入参数：
        //dwTimeOut：超时时间，默认为 5000，单位是毫秒。 
        //输出参数： 
        //cardid：读取到的身份证ID号。
        //pszRcCode：失败时返回 10 位错误码，成功时返回“0000000000”。
        //返回值：0-成功，其他-失败。
        [DllImport("GWI_IDCard_Driver.dll", EntryPoint = "IDCard_GetCardid")]
        public static extern int IDCard_GetCardid(int dwTimeOut, StringBuilder cardid, StringBuilder pszRcCode);

        [DllImport("GWI_IDCard_Driver.dll", EntryPoint = "IDCard_ReadIDCardMsgNum")]
        private static extern int IDCard_ReadIDCardMsgNum(int dwTimeOut, StringBuilder msg, StringBuilder pszRcCode);


        [DllImport("GWI_IDCard_Driver.dll", EntryPoint = "IDCard_ReadIDCardMsgNumExt")]
        private static extern int IDCard_ReadIDCardMsgNumExt(String photoName, int dwTimeOut, StringBuilder msg, StringBuilder pszRcCode);

        /// <summary>
        /// 获取设备状态
        /// </summary>
        /// <param name="dwTimeOut"></param>
        /// <param name="status"></param>
        /// <param name="pszRcCode"></param>
        /// <returns></returns>
        [DllImport("GWI_IDCard_Driver.dll", EntryPoint = "IDCard_GetStatus")]
        private static extern int IDCard_GetStatus(int dwTimeOut, ref int status, StringBuilder pszRcCode);

        /// <summary>
        /// 获取版本信息
        /// </summary>
        /// <param name="dwTimeOut"></param>
        /// <param name="Version"></param>
        /// <param name="pszRcCode"></param>
        /// <returns></returns>
        [DllImport("GWI_IDCard_Driver.dll", EntryPoint = "IDCard_GetVersion")]
        private static extern int IDCard_GetVersion(int dwTimeOut, StringBuilder Version, StringBuilder pszRcCode);

        /// <summary>
        /// 读三代身份证
        /// </summary>
        /// <param name="dwTimeOut">超时时间</param>
        /// <param name="sexNationflag">性别和民族代码标识</param>
        /// <param name="photoName">头像照片路径</param>
        /// <param name="msg">返回信息</param>
        /// <param name="reCode">返回码</param>
        /// <param name="pFPmsg">指纹信息</param>
        /// <returns>System.Int32</returns>
        [DllImport("GWI_IDCard_Driver.dll", EntryPoint = "IDCard_ReadBaseFPMsg")]
        private static extern int IDCard_ReadBaseFPMsg(int dwTimeOut, int sexNationflag, String photoName, StringBuilder msg, StringBuilder pFPmsg, StringBuilder pszRcCode);

        /// <summary>
        /// 读港澳台身份证
        /// </summary>
        /// <param name="dwTimeOut">超时时间</param>
        /// <param name="sexNationflag">性别和民族代码标识</param>
        /// <param name="photoName">头像照片路径</param>
        /// <param name="msg">返回信息</param>
        /// <param name="reCode">返回码</param>
        /// <returns>System.Int32</returns>
        [DllImport("GWI_IDCard_Driver.dll", EntryPoint = "IDCard_ReadGATBaseMsg")]
        private static extern int IDCard_ReadGATBaseMsg(int dwTimeOut, int sexNationflag, String photoName, StringBuilder msg, StringBuilder pszRcCode);

        /// <summary>
        /// 卡片状态
        /// </summary>
        /// <param name="dwTimeOut"></param>
        /// <param name="status"></param>
        /// <param name="pszRcCode"></param>
        /// <returns></returns>
        [DllImport("GWI_IDCard_Driver.dll", EntryPoint = "IDCard_GetMediaStatus")]
        private static extern int IDCard_GetMediaStatus(int dwTimeOut, ref int status, StringBuilder pszRcCode);


        #endregion

        #region  私有变量
        /// <summary>
        /// 超时时间
        /// </summary>
        private static int m_dwTimeOut = 5000;
        /// <summary>
        /// 返回码
        /// </summary>
        private static StringBuilder m_pszRcCode = new StringBuilder(260);

        #endregion

        private void Login(int ret)
        {
            tbLog.AppendText("返回值：" + ret.ToString());
            tbLog.AppendText("\r\n");
            tbLog.AppendText("返回码：" + m_pszRcCode.ToString());
            tbLog.AppendText("\r\n");
        }

        public void LogMsg(string msg)
        {
            tbLog.AppendText(msg + "\r\n");
        }

        private bool CheckTimeout()
        {
            bool ret = int.TryParse(this.tbTimeOut.Text, out m_dwTimeOut);
            if (!ret)
            {
                tbLog.AppendText("超时时间输入有误！无法调用接口测试。\r\n");
            }
            return ret;
        }

        private void ClearShowText()
        {
            this.tbDeviceId.Text = "";
            this.tbName.Text = "";
            this.tbSex.Text = "";
            this.tbNation.Text = "";
            this.tbBorn.Text = "";
            this.tbAddress.Text = "";
            this.tbIDNum.Text = "";
            this.tbPassID.Text = "";
            this.tbSignCnt.Text = "";
            this.tbCardType.Text = "";
            this.tbFPMsg.Text = "";
            pbPicture.Image = null;
        }

        private void btnSetParam_Click(object sender, EventArgs e)
        {
            string strType = cbDevType.Text;
            string strPort = tbDevPort.Text;
            string strParam = tbDevPortParam.Text;
            //int ret = IDCard_SetDeviceParam("GWI" ,"USB","9600,E,8,1",m_pszRcCode);
            int iResult = IDCard_SetDeviceParam(strType, strPort, strParam, m_pszRcCode);

            LogMsg(string.Format("IDCard_SetDeviceParam:ret={0}, errcode={1}", iResult.ToString(), m_pszRcCode.ToString()));
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            int iResult = 0;
            iResult = IDCard_OpenDevice(m_pszRcCode);
            LogMsg(string.Format("IDCard_OpenDevice:ret={0}, errcode={1}", iResult.ToString(), m_pszRcCode.ToString()));
        }

        private void btnReadID_Click(object sender, EventArgs e)
        {
            if (!CheckTimeout())
            {
                return;
            }
            ClearShowText();
            int iResult = 0;
            StringBuilder strRequest = new StringBuilder(512);
            iResult = IDCard_ReadIDCardMsg(m_dwTimeOut, strRequest, m_pszRcCode);

            if (iResult == 0)
            {
                string[] str = strRequest.ToString().Split('|');
                tbName.Text = str[0].Trim();
                tbSex.Text = str[1];
                tbNation.Text = str[2];
                tbBorn.Text = str[3];
                tbIDNum.Text = str[4];
                tbAddress.Text = str[5];
                string strPic = str[9];
                //Login(ret);
                if (File.Exists(strPic))
                {
                    Image img = Image.FromFile(strPic);
                    Image bmp = new Bitmap(img);
                    img.Dispose();
                    pbPicture.Image = bmp;
                }
            }

            LogMsg(string.Format("IDCard_ReadIDCardMsg:ret={0}, errcode={1}", iResult.ToString(), m_pszRcCode.ToString()));

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            int ret = IDCard_CloseDevice(m_pszRcCode);
            LogMsg(string.Format("IDCard_CloseDevice:ret={0}, errcode={1}", ret.ToString(), m_pszRcCode.ToString()));
        }

        private void btn_ClearLog_Click(object sender, EventArgs e)
        {
            this.tbLog.Text = "";
        }

        private void btn_OnlyReadCardId_Click(object sender, EventArgs e)
        {
            if (!CheckTimeout())
            {
                return;
            }
            StringBuilder pszRcCode = new StringBuilder(256);
            StringBuilder CardId = new StringBuilder(32);
            int iResult = 0;
            iResult = IDCard_GetCardid(m_dwTimeOut, CardId, pszRcCode);
            LogMsg(string.Format("IDCard_GetCardid:ret={0}, cardid={1}, errcode={2}", iResult.ToString(), CardId.ToString(), pszRcCode.ToString()));
        }

        private void btn_ReadDeviceId_Click(object sender, EventArgs e)
        {
            if (!CheckTimeout())
            {
                return;
            }
            StringBuilder pszRcCode = new StringBuilder(256);
            StringBuilder devId = new StringBuilder(128);
            int iResult = 0;
            iResult = IDCard_GetDevid(m_dwTimeOut, devId, pszRcCode);
            LogMsg(string.Format("IDCard_GetDevid:ret={0}, deviceId={1}, errcode={2}", iResult.ToString(), devId.ToString(), pszRcCode.ToString()));
            this.tbDeviceId.Text = devId.ToString();
        }

        private void btnReadIdByCode_Click(object sender, EventArgs e)
        {
            if (!CheckTimeout())
            {
                return;
            }
            ClearShowText();
            int ret = 0;
            StringBuilder strRequest = new StringBuilder(512);
            ret = IDCard_ReadIDCardMsgNum(m_dwTimeOut, strRequest, m_pszRcCode);
            if (ret == 0)
            {
                string[] str = strRequest.ToString().Split('|');
                tbName.Text = str[0].Trim();
                tbSex.Text = str[1];
                tbNation.Text = str[2];
                tbBorn.Text = str[3];
                tbIDNum.Text = str[4];
                tbAddress.Text = str[5];
                string strPic = str[9];

                if (File.Exists(strPic))
                {
                    Image img = Image.FromFile(strPic);
                    Image bmp = new Bitmap(img);
                    img.Dispose();
                    pbPicture.Image = bmp;
                }
            }

            LogMsg(string.Format("IDCard_ReadIDCardMsgNum:ret={0}, errcode={1}", ret.ToString(), m_pszRcCode.ToString()));
        }

        private void btnReadIdWithPath_Click(object sender, EventArgs e)
        {
            if (!CheckTimeout())
            {
                return;
            }
            ClearShowText();
            int ret = 0;
            string strCurrDir = this.tbPhotoDir.Text;

            StringBuilder strRequest = new StringBuilder(512);
            ret = IDCard_ReadIDCardMsgExt(strCurrDir, m_dwTimeOut, strRequest, m_pszRcCode);
            if (ret == 0)
            {
                string[] str = strRequest.ToString().Split('|');
                tbName.Text = str[0].Trim();
                tbSex.Text = str[1];
                tbNation.Text = str[2];
                tbBorn.Text = str[3];
                tbIDNum.Text = str[4];
                tbAddress.Text = str[5];
                string strPic = str[9];
                if (File.Exists(strPic))
                {
                    Image img = Image.FromFile(strPic);
                    Image bmp = new Bitmap(img);
                    img.Dispose();
                    pbPicture.Image = bmp;
                }
                else 
                {
                    strPic = strCurrDir.Substring(0, strCurrDir.LastIndexOf('\\') + 1) + "photo.bmp";
                    if (File.Exists(strPic))
                    {
                        Image img = Image.FromFile(strPic);
                        Image bmp = new Bitmap(img);
                        img.Dispose();
                        pbPicture.Image = bmp;
                    }
                }
            }
            LogMsg(string.Format("IDCard_ReadIDCardMsgExt:ret={0}, errcode={1}", ret.ToString(), m_pszRcCode.ToString()));
        }

        private void btnReadIdWithPathByCode_Click(object sender, EventArgs e)
        {
            if (!CheckTimeout())
            {
                return;
            }
            ClearShowText();
            int ret = 0;
            string strCurrDir = this.tbPhotoDir.Text;

            StringBuilder strRequest = new StringBuilder(512);
            ret = IDCard_ReadIDCardMsgNumExt(strCurrDir, m_dwTimeOut, strRequest, m_pszRcCode);
            if (ret == 0)
            {
                string[] str = strRequest.ToString().Split('|');
                tbName.Text = str[0].Trim();
                tbSex.Text = str[1];
                tbNation.Text = str[2];
                tbBorn.Text = str[3];
                tbIDNum.Text = str[4];
                tbAddress.Text = str[5];
                string strPic = str[9];

                if (File.Exists(strPic))
                {
                    Image img = Image.FromFile(strPic);
                    Image bmp = new Bitmap(img);
                    img.Dispose();
                    pbPicture.Image = bmp;
                }
                else
                {
                    strPic = strCurrDir.Substring(0, strCurrDir.LastIndexOf('\\') + 1) + "photo.bmp";
                    if (File.Exists(strPic))
                    {
                        Image img = Image.FromFile(strPic);
                        Image bmp = new Bitmap(img);
                        img.Dispose();
                        pbPicture.Image = bmp;
                    }
                }
            }
            LogMsg(string.Format("IDCard_ReadIDCardMsgNumExt:ret={0}, errcode={1}", ret.ToString(), m_pszRcCode.ToString()));

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string strCurrDir = System.Environment.CurrentDirectory + "\\photo.bmp";
            this.tbPhotoDir.Text = strCurrDir;
        }

        private void btnSetDeviceTraceLevel_Click(object sender, EventArgs e)
        {
            LogMsg("\r\n================");
            if (tbLevel.TextLength <= 4)
            {
                try
                {
                    int Level = Convert.ToInt32(tbLevel.Text, 16);
                    IDCard_SetDeviceTraceLevel(Level);
                    LogMsg("设置日志等级完成。");
                }
                catch (Exception)
                {
                    LogMsg("日志等级输入有误！无法调用接口测试。");
                }
            }
            else
            {
                LogMsg("日志等级输入有误！无法调用接口测试。");
            }
        }

        private void ReadMsgTest_Click(object sender, EventArgs e)
        {
            //btnOpen_Click(sender, e);

            //btn_ReadDeviceId_Click(sender, e);
            btnReadID_Click(sender, e);
            //btn_ReadDeviceId_Click(sender, e);
            btn_ClearLog_Click(sender, e);
            //btnClose_Click(sender, e);
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
        }

        private void btnEnd_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
        }

        private void timer1_Tick_1(object sender, EventArgs e)
        {
            ReadMsgTest_Click(sender, e);
        }

        private void btnGetVersion_Click(object sender, EventArgs e)
        {
            if (!CheckTimeout())
            {
                return;
            }
            StringBuilder version = new StringBuilder(512);
            int ret = IDCard_GetVersion(m_dwTimeOut, version, m_pszRcCode);
            LogMsg(string.Format("IDCard_GetVersion:ret={0}, version={1}, errcode={2}", ret.ToString(), version.ToString(), m_pszRcCode.ToString()));
        }

        private void btnGetStatus_Click(object sender, EventArgs e)
        {
            if (!CheckTimeout())
            {
                return;
            }
            int status = 0;
            int ret = IDCard_GetStatus(m_dwTimeOut, ref status, m_pszRcCode);
            LogMsg(string.Format("IDCard_GetStatus:ret={0}, status={1}, errcode={2}", ret.ToString(), status.ToString(), m_pszRcCode.ToString()));
        }

        private void btnReadFPMsg_Click(object sender, EventArgs e)
        {
            if (!CheckTimeout())
            {
                return;
            }
            ClearShowText();
            int iResult = 0;
            int sexNationFlag = 0;
            bool flag = int.TryParse(this.tbSexNationFlag.Text, out sexNationFlag);
            if(flag == false)
            {
                LogMsg(string.Format("IDCard_ReadFPMsg:参数输入有误，请核对"));
                return;
            }
            string strCurrDir = this.tbPhotoDir.Text;
            StringBuilder strRequest = new StringBuilder(512);
            StringBuilder pFPmsg = new StringBuilder(2048);
            iResult = IDCard_ReadBaseFPMsg(m_dwTimeOut, sexNationFlag, strCurrDir, strRequest, pFPmsg, m_pszRcCode);
            if (0 == iResult)
            {
                string[] str = strRequest.ToString().Split('|');
                tbName.Text = str[0].Trim();
                tbSex.Text = str[1];
                tbNation.Text = str[2];
                tbBorn.Text = str[3];
                tbIDNum.Text = str[4];
                tbAddress.Text = str[5];
                string strPic = str[9];
                tbFPMsg.Text = pFPmsg.ToString();
                if (File.Exists(strPic))
                {
                    Image img = Image.FromFile(strPic);
                    Image bmp = new Bitmap(img);
                    img.Dispose();
                    pbPicture.Image = bmp;
                }
                else
                {
                    strPic = strCurrDir.Substring(0, strCurrDir.LastIndexOf('\\') + 1) + "photo.bmp";
                    if (File.Exists(strPic))
                    {
                        Image img = Image.FromFile(strPic);
                        Image bmp = new Bitmap(img);
                        img.Dispose();
                        pbPicture.Image = bmp;
                    }
                }
            }

            LogMsg(string.Format("IDCard_ReadBaseFPMsg:ret={0}, errcode={1}", iResult.ToString(), m_pszRcCode.ToString()));
        }

        private void btnReadGATBaseMsg_Click(object sender, EventArgs e)
        {
            if (!CheckTimeout())
            {
                return;
            }
            ClearShowText();
            int iResult = 0;
            int sexNationFlag = 0;
            bool flag = int.TryParse(this.tbSexNationFlag.Text, out sexNationFlag);
            if(flag == false)
            {
                LogMsg(string.Format("IDCard_ReadFPMsg:参数输入有误，请核对"));
                return;
            }
            string strCurrDir = this.tbPhotoDir.Text;
            StringBuilder strRequest = new StringBuilder(512);
            iResult = IDCard_ReadGATBaseMsg(m_dwTimeOut, sexNationFlag, strCurrDir, strRequest, m_pszRcCode);
            if (0 == iResult)
            {
                string[] str = strRequest.ToString().Split('|');
                int lenth = str.Length;
                tbName.Text = str[0].Trim();
                tbSex.Text = str[1];
                tbNation.Text = str[2];
                tbBorn.Text = str[3];
                tbIDNum.Text = str[4];
                tbAddress.Text = str[5];       
                tbPassID.Text = str[10];
                tbSignCnt.Text = str[11];
                tbCardType.Text = str[13];
                string strPic = str[9];

                if (File.Exists(strPic))
                {
                    Image img = Image.FromFile(strPic);
                    Image bmp = new Bitmap(img);
                    img.Dispose();
                    pbPicture.Image = bmp;
                }
                else
                {
                    strPic = strCurrDir.Substring(0, strCurrDir.LastIndexOf('\\') + 1) + "photo.bmp";
                    if (File.Exists(strPic))
                    {
                        Image img = Image.FromFile(strPic);
                        Image bmp = new Bitmap(img);
                        img.Dispose();
                        pbPicture.Image = bmp;
                    }
                }
            }

            LogMsg(string.Format("IDCard_ReadGATBaseMsg:ret={0}, errcode={1}", iResult.ToString(), m_pszRcCode.ToString()));

        }

        private void btnCardStatus_Click(object sender, EventArgs e)
        {
            if (!CheckTimeout())
            {
                return;
            }
            int status = 0;
            int ret = IDCard_GetMediaStatus(m_dwTimeOut, ref status, m_pszRcCode);
            LogMsg(string.Format("IDCard_GetMediaStatus:ret={0}, status={1}, errcode={2}", ret.ToString(), status.ToString(), m_pszRcCode.ToString()));
        }
    }
}
